import psutil
import time

def get_php_process_cpu_time():
    # 遍历所有进程，找到 PHP 进程（假设 PHP 进程的名字为 'php'）
    for proc in psutil.process_iter(['pid', 'name', 'cpu_times']):
        if 'php' in proc.info['name'].lower():  # 假设 PHP 进程名包含 'php'
            print(f"proc.info['cpu_times'].user:{proc.info['cpu_times'].user}")
            print(f"proc.info['cpu_times'].system:{proc.info['cpu_times'].system}")
            return proc.info['cpu_times'].user + proc.info['cpu_times'].system
    print("fail to find php process")
    return 0  # 如果没有找到 PHP 进程，返回 0

def get_system_cpu_time():
    # 获取系统的 CPU 使用时间
    cpu_times = psutil.cpu_times()
    return cpu_times.user + cpu_times.system

# 设置时间间隔（单位：秒）
interval = 5

# 获取初始时刻的 CPU 时间
initial_system_cpu_time = get_system_cpu_time()
initial_php_cpu_time = get_php_process_cpu_time()

# 等待时间间隔
time.sleep(interval)

# 获取结束时刻的 CPU 时间
final_system_cpu_time = get_system_cpu_time()
final_php_cpu_time = get_php_process_cpu_time()

# 计算时间间隔内的 CPU 时间变化
system_cpu_time_delta = final_system_cpu_time - initial_system_cpu_time
php_cpu_time_delta = final_php_cpu_time - initial_php_cpu_time

# 防止除以零错误
if system_cpu_time_delta > 0:
    cpu_usage_ratio = php_cpu_time_delta / system_cpu_time_delta
    print(f"php_time:{php_cpu_time_delta}")
    print(f"system_cpu_time_delta:{system_cpu_time_delta}")
    print(f"PHP process CPU time ratio over system CPU time: {cpu_usage_ratio:.4f}")
else:
    print("Error: System CPU time delta is zero or negative.")
